/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import API_Jung.MyMouseMenus;
import API_Jung.PopupVertexEdgeMenuMousePlugin;
import ProcessData.DataFile;
import edu.uci.ics.jung.algorithms.layout.KKLayout;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.SparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import edu.uci.ics.jung.visualization.LayeredIcon;
import edu.uci.ics.jung.visualization.VisualizationImageServer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import pw.analyzer.Edge;
import pw.analyzer.Node;

/**
 *
 * @author Heitor
 */
public class JFInitial extends javax.swing.JFrame {

    private String title; //Titulo do software
    
    private int nodetype, nodecount, nVertex, nEdges;
    
    //Variaveis do JUNG
    private DirectedSparseGraph<Node, String> g; //Grafo da tela principal
    private SparseGraph<Node, String> g1; //Grafo auxiliar
    
    private VisualizationViewer<Node, String> vv;
    private KKLayout<Node, String> layout;
    private JScrollPane graphScroll;
    private EditingModalGraphMouse<Node, String> graphMouse;
    
    private float alpha = 0.3f;
    private Rectangle xy;
    
    private Node start, end;
    
    private DataFile dataFile; //Classe que processa os dados vindo do arquivo .txt
    
    //Variável auxiliares no carregamento de dados
    private ArrayList<Node> listVertex = new ArrayList<Node>();
    private ArrayList<Edge> listEdge = new ArrayList<Edge>();
    
    private Boolean[] aux_vertex;
    private boolean aux_mode;
    private Node node_auxShow; 
    
    private Image image_GraphScreen;// = new ImageIcon(getClass().getResource("/ImageFiles/Logo.png")).getImage();
    
    /**
     * Creates new form JFInitial
     */
    public JFInitial(String title) {
        initComponents();
        
        //Configuração da tela
        this.title = title;
        setTitle(this.title);
        Icon icon = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/Logo.png")).getImage());
        logo.setIcon(icon);
        ImageIcon imagemTituloJanela = new ImageIcon(getClass().getResource("/ImageFiles/icon_PW.png"));  
        setIconImage(imagemTituloJanela.getImage());
        Icon icon1 = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/User3.png")).getImage());
        jlUser.setIcon(icon1);
        this.setMinimumSize(new Dimension(750,450));
        
        createToolBar();
        
        this.setExtendedState(MAXIMIZED_BOTH);
        
        //Inicialização de variáveis
        dataFile = new DataFile();
        nodetype = 0;
        nodecount = 0;
        nVertex = 1;
        nEdges = 1;
        aux_vertex = new Boolean[nVertex];
        aux_mode = false;
        
        jpHelper.setBackground(Color.GRAY);
        
        helper.setBackground(Color.GRAY);
        helper.setText("Olá, Seja bem-vindo! \nAqui você terá ajuda em todos os processos do PW-Analyzer, podendo ser usado as dicas como passo-a-passo.");
        
        jFileChooser1.setDialogTitle("[Arquivo de Dados]");
        jFileChooser1.setFileFilter(new javax.swing.filechooser.FileFilter(){
            //Filtro, converte as letras em minúsculas antes de comparar
            @Override
            public boolean accept(File f){
                return f.getName().toLowerCase().endsWith(".txt") || f.isDirectory();
            }
            //Texto que será exibido para o usuário
            @Override
            public String getDescription() {
                return "Arquivos de dados (.txt)";
            }
        });
        
        jFileChooser2.setDialogTitle("[Imagem da planta]");
        jFileChooser2.setFileFilter(new javax.swing.filechooser.FileFilter(){
            //Filtro, converte as letras em minúsculas antes de comparar
            @Override
            public boolean accept(File f){
                return f.getName().toLowerCase().endsWith(".png") 
                        || f.getName().toLowerCase().endsWith(".jpg")
                        || f.isDirectory();
            }
            //Texto que será exibido para o usuário
            @Override
            public String getDescription() {
                return "Imagem da planta (.png ou .jpg)";
            }
        });
        
        jFileChooser3.setDialogTitle("");
        jFileChooser3.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        
        configAction(); //Realiza as configurações de ações do usuario na aplicação
        
    }
    
    /*
     * Cria a barra de ferramentas da tela
     */
    public final void createToolBar() {
        
        this.b_Open.setToolTipText("Carregar Arquivo");
        
        b_Open.setVisible(true);
    }

    private void configAction(){
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing (WindowEvent e) {
                //Nesta parte devemos colocar todo o que queremos que aconteça quando o botão
                //fechar for pressionado, neste caso apenas é exibida uma mensagem simples
                //e depois a aplicação é encerrada.
            }
        });
    }

    /*
     * Constrói a tela com os dados de "dataFile"
     */
    public final void reloadGraphScreen() {
        
        JTabbedPane GraphS = new JTabbedPane();
        
        g = new DirectedSparseGraph<Node, String>(); //Apenas para iniciar o layout em grafo null
        g1 = new SparseGraph<Node, String>();
        
        layout = new KKLayout(g);
        
        vv = new VisualizationViewer<Node, String>(layout)
        {
            @Override
            protected void paintComponent(java.awt.Graphics g) {
                super.paintComponent(g);
                
                if(image_GraphScreen != null){
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
                    g2d.drawImage(image_GraphScreen, 0, 0, this);
                }else{
                    //System.out.println("** Nenhuma imagem de planta foi carregada! **");
                }
            };
        };
        vv.setBackground(Color.WHITE);
        vv.setForeground(Color.BLACK);
        vv.setOpaque(true);
        
        //Colocando o vetor de boolean tdo em TRUE
        aux_vertex = new Boolean[dataFile.getListNode().size()];
        for(int h=0; h<aux_vertex.length; h++){
            aux_vertex[h] = true;
        }
        
        //
        //Criação do grafo a partir da lista de arestas recebidas
        //
        Node node_aux;
        for(Iterator i = dataFile.getListNode().iterator(); i.hasNext();){
            node_aux = (Node)i.next();
            //Enviando para todos os testes do grafo da janela principal
            g1.addVertex(node_aux);
            listVertex.add(node_aux);
            if(node_aux.getType() == 0){ 
                start = node_aux; 
            }else if(node_aux.getType() == 1){ 
                end = node_aux; 
            }else if(node_aux.getType() == 2){
                nVertex++;
            }
            
        }
        
        listEdge = dataFile.getListEdge();
        
        for(Iterator i = listEdge.iterator(); i.hasNext();){
            Edge edge = (Edge)i.next();
            
            g1.addEdge(edge.getEdge() + " _ " + edge.getValue(), processNode(edge.getIdOrigem()), processNode(edge.getIdDestino()), EdgeType.UNDIRECTED);
            nEdges++;
        }      
        
        
        //
        //Setando o layout no visualization view
        //
        
        //Setando os nomes dos vertices
        vv.getRenderContext().setVertexLabelTransformer(new Transformer<Node, String>() {
            @Override
            public String transform(Node v) {
                switch (v.getType()) {
                    case 0:
                        return "Inicio";
                    case 1:
                        return "Final";
                    case 2:
                        return "Nó " + v.getCatid();
                }
                return "Erro";
            }
        });
        
        vv.getRenderContext().setEdgeLabelTransformer(new Transformer<String, String>() {

            @Override
            public String transform(String e) {
                String aux = "";
                StringTokenizer st = new StringTokenizer(e, "_ ");  
                while (st.hasMoreTokens()){
                    aux = st.nextToken();
                }
                
                return aux + " dBm";
            }
        });
        
        vv.setGraphLayout(layout);
        vv.getRenderContext().setVertexIconTransformer(
                new MyVertexIconTransformerReloadGraph<Node>());
        Factory<Node> vertexFactory = new JFInitial.VertexFactory();
        Factory<String> edgeFactory = new JFInitial.EdgeFactory();
        graphMouse = new EditingModalGraphMouse<Node, String>(vv.getRenderContext(), vertexFactory, edgeFactory);

        //
        //Adicionando alguns "popup menus" para os vertices e arestas para o "mouse plugin"
        //
        
        PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
        
        JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();

        JPopupMenu EdgeMenu = new MyMouseMenus.EdgeMenu();

        myPlugin.setVertexPopup(vertexMenu);
        myPlugin.setEdgePopup(EdgeMenu);
        graphMouse.remove(graphMouse.getPopupEditingPlugin());  // Removes the existing popup editing plugin

        graphMouse.add(myPlugin);   // Add our new plugin to the mouse

        //
        //Setando plugins do mouse
        //
        vv.setGraphMouse(graphMouse);
        vv.addKeyListener(graphMouse.getModeKeyListener());

        //
        //Setando o modo do mouse na tela. "TRANSFORMING" transforme apenas modifica o lugar do grafo como um todo.
        //
        
        //graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
        graphMouse.setMode(ModalGraphMouse.Mode.EDITING);
        
        nEdges = g1.getEdgeCount();
        nodecount = g1.getVertexCount();

        //
        //Setando o visualization view no graphScroll(ScrollBar)
        //
        graphScroll = new JScrollPane();
        graphScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        graphScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        graphScroll.setViewportView(vv);
        //graphScroll.setSize(this.GraphScreen.getSize());

        //GraphS.addTab("Net Virtual", graphScroll);

        GraphScreen.setLayout(new BorderLayout());
        //GraphScreen.add("Center", GraphS);
        GraphScreen.add("Center", graphScroll);
        
        //Colocando o titulo
        setTitle(dataFile.getNome() + " - " + title);
        
        helper.setText("Passo: Clique para adicionar o " + listVertex.get(0).getNome());
        
    }
    
    private Node processNode(int id){
        
        Node node = null;
        
        for(Iterator i = listVertex.iterator(); i.hasNext();){
            Node node_aux = (Node)i.next();
            
            if(node_aux.getId() == id){
                node = node_aux;
            }
        }
        return node;
        
    }

    public class MyVertexIconTransformerReloadGraph<Node> implements
            Transformer<Node, Icon> {

        @Override
        public Icon transform(Node n) {
            String[] n2 = n.toString().split("nici");
            String[] n3 = n.toString().split("ina");
            Icon icone;
                
            if (n2.length > 1) {
                icone = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/StartBall.png")).getImage());
                start.setState(3);
            } else if (n3.length > 1) {
                icone = new LayeredIcon(new ImageIcon(getClass().getResource("/ImageFiles/EndNode.png")).getImage());
            } else {
                icone = new LayeredIcon(new ImageIcon(getClass().getResource(readIcon(g1, n.toString()))).getImage());
            }
            
            if(aux_mode){
                graphMouse.setMode(ModalGraphMouse.Mode.PICKING);
            } else {
                if(node_auxShow != null){
                    helper.setText("Passo: Clique para adicionar o " + node_auxShow.getNome());
                }else {
                    helper.setText("Passo: Clique para adicionar o primeiro instrumento");
                }
            }
            
            return icone;
        }
    }    

    public class VertexFactory implements Factory<Node> {

        /**
         * Ativada com o modo EDITING
         * @return Node
         */
        @Override
        public Node create() {
            
            Node node = null;
            
            node = locationComponents();
            
            return node;
            //return new Node(nodecount++, nodetype, 0);
        }
    }

    public class EdgeFactory implements Factory<String> {

        @Override
        public String create() {
            return "" + nEdges++;
        }
    }
  
    
    /*
     * Método que, através do estado, define o icone do nó.
     */
    private String readIcon(SparseGraph<Node, String> g, String nome){
        String aux1 = ("/ImageFiles/" + "instrumento_60x60.png");
        
        for (Iterator it = g.getEdges().iterator(); it.hasNext();) { // percorre todas as arestas
            String edge = (String) it.next();

            if((g.getEndpoints(edge).getFirst().getId() == 0)&&(g.getEndpoints(edge).getFirst().getNome().equals(nome))){
                aux1 = ("/ImageFiles/" + "gateway_60x60.png");
            }            
        }
        return (aux1);
    }
    
    private Node locationComponents(){
        
            Node node = null;
        
            int id = -1;

            boolean x = true;
            int h = 0;
            
            /**
             * Escolhe o id do node a ser adicionado
             */
            while(x && (h<aux_vertex.length)){
                if(aux_vertex[h]){
                    id = h;
                    aux_vertex[h] = false;
                    x = false;
                }
                h++;
            }
            
            /**
             * Procura o node a ser adicionado na rede
             */
            for(Iterator i = listVertex.iterator(); i.hasNext();){
                Node node_aux = (Node)i.next();
                
                if(node_aux.getId() == id){
                    node = node_aux;
                    node_auxShow = node_aux;
                } else if(node_aux.getId() == id+1){
                    node_auxShow = node_aux;
                }
            }
            
            /**
             * Se for o ultimo node a colocar na rede deve mostrar a rede e deixar em modo de PICKING
             */
            if(aux_vertex.length-1 == id){
                if(graphMouse != null){
                    aux_mode = true;
                    layout.setGraph(g1);
                    helper.setText("Sua rede de instrumentos está pronta! Você ainda pode modificar a localização de um instrumento clicando em cima deste.");
                }
            }
            
            return node;
        
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jFileChooser2 = new javax.swing.JFileChooser();
        jFileChooser3 = new javax.swing.JFileChooser();
        jToolBar1 = new javax.swing.JToolBar();
        b_Open = new javax.swing.JButton();
        b_OpenImage = new javax.swing.JButton();
        b_createImage = new javax.swing.JButton();
        GraphScreen = new javax.swing.JPanel();
        logo = new javax.swing.JLabel();
        jpHelper = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        helper = new javax.swing.JTextArea();
        jlUser = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setRollover(true);

        b_Open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/13.png"))); // NOI18N
        b_Open.setFocusable(false);
        b_Open.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        b_Open.setMaximumSize(new java.awt.Dimension(29, 29));
        b_Open.setMinimumSize(new java.awt.Dimension(29, 29));
        b_Open.setPreferredSize(new java.awt.Dimension(29, 29));
        b_Open.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        b_Open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                b_OpenActionPerformed(evt);
            }
        });
        jToolBar1.add(b_Open);

        b_OpenImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/32.png"))); // NOI18N
        b_OpenImage.setFocusable(false);
        b_OpenImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        b_OpenImage.setMaximumSize(new java.awt.Dimension(29, 29));
        b_OpenImage.setMinimumSize(new java.awt.Dimension(29, 29));
        b_OpenImage.setPreferredSize(new java.awt.Dimension(29, 29));
        b_OpenImage.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        b_OpenImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                b_OpenImageActionPerformed(evt);
            }
        });
        jToolBar1.add(b_OpenImage);

        b_createImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/19.png"))); // NOI18N
        b_createImage.setFocusable(false);
        b_createImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        b_createImage.setMaximumSize(new java.awt.Dimension(29, 29));
        b_createImage.setMinimumSize(new java.awt.Dimension(29, 29));
        b_createImage.setPreferredSize(new java.awt.Dimension(29, 29));
        b_createImage.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        b_createImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                b_createImageActionPerformed(evt);
            }
        });
        jToolBar1.add(b_createImage);

        javax.swing.GroupLayout GraphScreenLayout = new javax.swing.GroupLayout(GraphScreen);
        GraphScreen.setLayout(GraphScreenLayout);
        GraphScreenLayout.setHorizontalGroup(
            GraphScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, GraphScreenLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(logo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        GraphScreenLayout.setVerticalGroup(
            GraphScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(GraphScreenLayout.createSequentialGroup()
                .addComponent(logo)
                .addGap(0, 213, Short.MAX_VALUE))
        );

        jScrollPane1.setBorder(null);

        helper.setColumns(20);
        helper.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        helper.setRows(5);
        helper.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        helper.setEnabled(false);
        helper.setMargin(new java.awt.Insets(5, 3, 2, 2));
        helper.setSelectionColor(new java.awt.Color(0, 0, 0));
        jScrollPane1.setViewportView(helper);

        javax.swing.GroupLayout jpHelperLayout = new javax.swing.GroupLayout(jpHelper);
        jpHelper.setLayout(jpHelperLayout);
        jpHelperLayout.setHorizontalGroup(
            jpHelperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpHelperLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlUser))
        );
        jpHelperLayout.setVerticalGroup(
            jpHelperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpHelperLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlUser)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );

        jMenu1.setText("Arquivo");

        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/12.png"))); // NOI18N
        jMenuItem1.setText("Carregar Dados");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);
        jMenu1.add(jSeparator1);

        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/19.png"))); // NOI18N
        jMenuItem2.setText("Carregar Planta");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);
        jMenu1.add(jSeparator2);

        jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/26.png"))); // NOI18N
        jMenuItem3.setText("Sair");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ajuda");

        jMenuItem4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ImageFiles/31.png"))); // NOI18N
        jMenuItem4.setText("Sobre o PW-Coletor");
        jMenu2.add(jMenuItem4);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jpHelper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(GraphScreen, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpHelper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(GraphScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void b_OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_OpenActionPerformed
        // TODO add your handling code here:
        
        jFileChooser1.setDialogTitle("Abrir " + "[Arquivo de Metodologia]");

        int returnVal = jFileChooser1.showOpenDialog(this);
        String diretorio = "";
        
        if (returnVal == JFileChooser.APPROVE_OPTION) {
        
            File file = jFileChooser1.getSelectedFile();
            diretorio = file.getAbsolutePath();
            dataFile = new DataFile(diretorio);

            System.out.println("** Carregou dados com sucesso! **");
            aux_mode = false;
            
            xy = GraphScreen.getBounds();
            
            GraphScreen.setVisible(false);
            getContentPane().remove(GraphScreen); //Remove o painel
            GraphScreen = new JPanel();
            GraphScreen.setBounds(xy);
            
            if (!dataFile.getListNode().isEmpty()) {
                logo.setVisible(false);
                getContentPane().add(GraphScreen); //Adiciona o novo painel
                reloadGraphScreen();
                GraphScreen.setVisible(true);
            } else {
                vv.setVisible(false);
            }
        }
        
    }//GEN-LAST:event_b_OpenActionPerformed

    private void b_OpenImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_OpenImageActionPerformed
        // TODO add your handling code here:

        jFileChooser2.setDialogTitle("Abrir " + "[Imagem da planta]");

        int returnVal = jFileChooser2.showOpenDialog(this);
        String diretorio = "";

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser2.getSelectedFile();
            diretorio = file.getAbsolutePath();
            String[] aux1_diretorio = diretorio.split("\\\\");
            String aux2_diretorio = "";
            for(int i=0; i<aux1_diretorio.length; i++){
                if(i != aux1_diretorio.length-1){
                    aux2_diretorio = aux2_diretorio + aux1_diretorio[i] + "/";
                } else{
                    aux2_diretorio = aux2_diretorio + aux1_diretorio[i];
                }
            }
            
            image_GraphScreen = Toolkit.getDefaultToolkit().getImage(aux2_diretorio);

            System.out.println("** Carregou imagem com sucesso! **");
            System.out.println("Imagem: "+ aux2_diretorio);

            JOptionPane.showMessageDialog(null, "Carregou Imagem com sucesso!", "Aviso", JOptionPane.INFORMATION_MESSAGE);
            
            //vv.validate();
        }        
        
    }//GEN-LAST:event_b_OpenImageActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    /**
     * Item do Menu "Arquivo" - botão de "Sair"
     * @param evt 
     */
    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        // TODO add your handling code here:
        
        int response;

        response = JOptionPane.showConfirmDialog(null, "Deseja sair do programa?", "Aviso", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION){
            System.exit(0);
        }

    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void b_createImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_createImageActionPerformed
        // TODO add your handling code here:
        
        int response;

        response = JOptionPane.showConfirmDialog(null, "Deseja gerar a imagem da planta final?", "Aviso", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION){
            
            jFileChooser3.setDialogTitle("Escolha um diretorio para salvar!");

            if(jFileChooser3.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
                
                String[] aux1_diretorio = jFileChooser3.getSelectedFile().getAbsolutePath().split("\\\\");
                String aux2_diretorio = "";
                for(int i=0; i<aux1_diretorio.length; i++){
                    if(i != aux1_diretorio.length-1){
                        aux2_diretorio = aux2_diretorio + aux1_diretorio[i] + "/";
                    } else{
                        aux2_diretorio = aux2_diretorio + aux1_diretorio[i];
                    }
                }
                System.out.println("O diretório é: "+ aux2_diretorio);
                createGraphImage(vv, aux2_diretorio);
            }
        }
        
    }//GEN-LAST:event_b_createImageActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel GraphScreen;
    private javax.swing.JButton b_Open;
    private javax.swing.JButton b_OpenImage;
    private javax.swing.JButton b_createImage;
    private javax.swing.JTextArea helper;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFileChooser jFileChooser2;
    private javax.swing.JFileChooser jFileChooser3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel jlUser;
    private javax.swing.JPanel jpHelper;
    private javax.swing.JLabel logo;
    // End of variables declaration//GEN-END:variables

    
    /**
     * Creates graph image PNG file from a BasicVisualizationServer
     * @param vv BasicVisualizationServer
     * @param imagePath Image full creation path
     */
     private void createGraphImage(VisualizationViewer<Node,String> vv, String imagePath) {
         
         DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
         Date date = new Date();
         String dataString = dateFormat.format(date);
         
         Transformer<String, Paint> edgePaint = new Transformer<String, Paint>() {
             private final Color[] palette = { Color.BLACK };

             @Override
             public Paint transform(String i) {                 
                return palette[0];
             }
         };
         
         Transformer<String, String> edgeLabel = new Transformer<String, String>() {
             
             @Override
             public String transform(String i){
                String aux = "";
                StringTokenizer st = new StringTokenizer(i, "_ ");  
                while (st.hasMoreTokens()){
                    aux = st.nextToken();
                }

                return aux + " dBm";
             }
         };
         
         Transformer<Node, Icon> vertexIcon = new Transformer<Node, Icon>(){
            
            @Override
            public Icon transform(Node n) {
            
                Icon icone;

                icone = new LayeredIcon(new ImageIcon(getClass().getResource(readIcon(g1, n.toString()))).getImage());

                return icone;
            }
         };

         // Convert graph to png
         VisualizationImageServer<Node, String> vis = new VisualizationImageServer<Node, String>(vv.getGraphLayout(), graphScroll.getSize())
         {
            @Override
            protected void paintComponent(java.awt.Graphics g) {
                super.paintComponent(g);
                
                if(image_GraphScreen != null){
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
                    g2d.drawImage(image_GraphScreen, 0, 0, this);
                }else{
                    //System.out.println("** Nenhuma imagem de planta foi carregada! **");
                    JOptionPane.showMessageDialog(null, "Nenhuma Imagem de Planta foi carregada!", "Aviso", JOptionPane.INFORMATION_MESSAGE);
                }
            };
         };

         // Set graph properties
         vis.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<Node>());
         vis.getRenderer().getVertexLabelRenderer().setPosition(Position.AUTO);
         vis.getRenderContext().setEdgeDrawPaintTransformer(edgePaint);
         vis.getRenderContext().setEdgeLabelTransformer(edgeLabel);
         vis.getRenderContext().setVertexIconTransformer(vertexIcon);

         // Create buffered image
         BufferedImage image = (BufferedImage) vis.getImage(new Point2D.Double(0,0), GraphScreen.getSize());
         
         // Output buffered image to png file
         File outputfile = new File(imagePath + "/Imagem_" + dataString + ".png");

         try {
            ImageIO.write(image, "png", outputfile);
            JOptionPane.showMessageDialog(null, "Imagem gerada com sucesso!", "Aviso", JOptionPane.INFORMATION_MESSAGE);
         } catch (Exception e) {
            System.out.println("Error");
            JOptionPane.showMessageDialog(null, "Erro na geração da imagem!", "Aviso", JOptionPane.ERROR_MESSAGE);
         }

     }
     
}